from collections import Counter

from sklearn.datasets import fetch_openml
import numpy as np
import pinecone
# 加载 MNIST 数据集
mnist = fetch_openml('mnist_784', version=1)
X, y = mnist["data"], mnist["target"]

# 连接到 Pinecone
pinecone.init("mnist-index", "120457e3-cd8e-4d78-8208-6b016c02bf75")

# 创建索引
index_name = "mnist-index"
if index_name not in pinecone.list_indexes():
    pinecone.create_index(
        name=index_name,
        dimension=784,  # MNIST 数据集的特征数量
        metric="euclidean",
        pod_type="s-1"
    )

# 上传数据
for i, (image, label) in enumerate(zip(X, y)):
    pinecone.upsert(index_name, [image.tolist()], metadata=[{"label": str(label)}])
import gradio as gr


def predict_digit(image):
    # 预处理图像并转换为相同的格式
    processed_image = image.reshape(784).tolist()

    # 在 Pinecone 中查询
    results = pinecone.query(index_name, processed_image, top_k=5)

    # 获取最常见的标签
    labels = [int(match['metadata']['label']) for match in results['matches']]
    most_common = Counter(labels).most_common(1)
    if most_common[0][1] > 1:  # 简单的共识投票
        return most_common[0][0]
    return "Unknown"


iface = gr.Interface(fn=predict_digit, inputs=gr.Image(shape=(28, 28)), outputs="text")
iface.launch()